package leetcode;

import java.util.HashMap;

public class FractionToRecurringDecimal {

	public static void main(String[] args) {
		FractionToRecurringDecimal object = new FractionToRecurringDecimal();
		System.out.println(object.fractionToDecimal(-1, Integer.MIN_VALUE));
	}
	
	public String fractionToDecimal(int numerator, int denominator) {
		if (denominator == 0) {
			return "NaN";
		}
		// 两个整数相除，结果要么能够除尽，要么是无限循环小数
		HashMap<Long, Integer> map = new HashMap<Long, Integer>();
		boolean negative = false;
		if( (numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0)){
			negative = true;
		}
		long numeratorLong = numerator;
		long denominatorLong = denominator;
		numeratorLong = Math.abs(numeratorLong);
		denominatorLong = Math.abs(denominatorLong);
		long divider = numeratorLong / denominatorLong;
		long mod = numeratorLong % denominatorLong;
		StringBuilder sb = new StringBuilder();
		if(negative){
			sb.append('-');
		}
		sb.append(divider);
		if(mod == 0){
			return sb.toString();
		}
		//还要考虑是负数的情况
		if(mod < 0){
			mod = -mod;
		}
		map.put(mod, 0);
		boolean circute = false;
		StringBuilder decimal = new StringBuilder();
		int index = 1;
		while (mod != 0) {
			numeratorLong = mod * 10;
			divider = numeratorLong / denominatorLong;
			mod = numeratorLong % denominatorLong;
			decimal.append(divider);
			if (map.containsKey(mod)) {
				index = map.get(mod);
				circute = true;
				break;
			}else{
				map.put(mod, index++);
			}
		}
		if (circute) {
			//有一点不对,比如1/6,结果应该是0.1(6),但是我们的结果是0.(16)
			//也就是说我们把不重复的也包含进来了
			sb.append('.');
			for(int i = 0; i < index; i++){
				sb.append(decimal.charAt(i));
			}
			sb.append('(');
			int length = decimal.length();
			for(int i = index; i < length; i++){
				sb.append(decimal.charAt(i));
			}
			sb.append(')');
		} else {
			sb.append('.').append(decimal);
		}
		return sb.toString();
	}
}
